package cn.hengzhu.main_manager.utils.httpssl;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import cn.hengzhu.main_manager.utils.config.xcx.WxConfig;

@SuppressWarnings("deprecation")
public class ClientCustomSSL {

	public static String postData(String url, String paramBuffer) throws Exception {
		String result = null;
		String key = WxConfig.MCH_ID;
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		// FileInputStream instream = new FileInputStream(new
		// File("C:/Users/lucky/Desktop/shdeyusaahuiu.p12"));
		
//		FileInputStream instream = new FileInputStream(new File("F:/工作/共享柜系统/shdeyusaahuiu.p12"));
		FileInputStream instream = new FileInputStream(new File("/etc/shdeyusaahuiu.p12"));
		try {
			keyStore.load(instream, key.toCharArray());
		} finally {
			instream.close();
		}

		// Trust own CA and all self-signed certs
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
		// Allow TLSv1 protocol only

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		try {

			HttpPost httpPost = new HttpPost(url);
			StringEntity postEntity = new StringEntity(paramBuffer, "UTF-8");
			httpPost.setHeader("Content-Type", "text/xml");
			httpPost.setEntity(postEntity);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "UTF-8");
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
		return result;
	}

}
